<?php


namespace app\admin\controller;


use api\crm\model\ConnectLogModel;
use api\crm\model\IntentionTagModel;
use app\admin\model\RoleUserModel;
use app\admin\model\UserModel;
use cmf\controller\AdminBaseController;

class ConnectLogController extends AdminBaseController
{
    public function logs()
    {
        $admin_id = cmf_get_current_admin_id();
        $role_id = RoleUserModel::where('user_id', $admin_id)->value('role_id');
        $role_id = $role_id ? $role_id : 1;
        $this->assign('role_id', $role_id);
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $user_info = UserModel::get($admin_id);
            $where[] = ['type', '=', 0];
            if ($user_info['company_id']) {
                $where[] = ['company_id', '=', $user_info['company_id']];
            }
            if (isset($data['duration']) && $data['duration']) {
                $where[] = ['create_time', 'between time', $data['duration']];
            }
            $num = 10;
            $page = isset($data['page']) && $data['page'] ? intval($data['page']) : 1;
            $list = ConnectLogModel::with(['user_info', 'customer_info', 'progress_status', 'customer_status', 'company_info'])
                ->where($where)
                ->order('create_time desc')
                ->paginate($num, false, ['page' => $page])
                ->each(function ($item) {
                    if ($item['tag_ids']) {
                        $temp_tag = [];
                        $array = explode(',', $item['tag_ids']);
                        foreach ($array as $value) {
                            $temp_tag[] = IntentionTagModel::get($value)['name'];
                        }
                        $item['tag_ids'] = $temp_tag;
                    }
                    if ($item['img_url']) {
                        $temp_array = [];
                        $array = explode(',', $item['img_url']);
                        foreach ($array as $value) {
                            $temp_array[] = $value;
                        }
                        $item['img_url'] = $temp_array;
                    }
                    if ($item['order_pic']) {
                        $temp_array = [];
                        $array = explode(',', $item['order_pic']);
                        foreach ($array as $value) {
                            $temp_array[] = $value;
                        }
                        $item['order_pic'] = $temp_array;
                    }
                    return $item;
                });
            $this->success('', '', $list);
        }
        return $this->fetch();
    }

    public function export()
    {
        $data = $this->request->param();
        $admin_id = cmf_get_current_admin_id();
        $user_info = UserModel::get($admin_id);
        $where = [];
        if (isset($data['duration']) && $data['duration']) {
            $where[] = ['create_time', 'between time', $data['duration']];
        }
        if ($user_info['company_id']) {
            $where[] = ['company_id', '=', $user_info['company_id']];
        }
        $where[] = ['type', '=', 0];
        $list = ConnectLogModel::with(['user_info', 'customer_info', 'progress_status', 'customer_status', 'company_info'])
            ->where($where)
            ->order('create_time desc')
            ->select()->each(function ($item) {
                if ($item['create_time']) {
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                }
                return $item;
            });
        $xlsCell = array(
            array('id', '序号'),
            array('admin_name', '操作人'),
            array('admin_role_name', '角色'),
            array('customer_info', '客户姓名', 'true_name'),
            array('customer_status_name', '操作类型'),
            array('status', '审核状态'),
            array('create_time', '操作时间'),
            array('area', '区'),
            array('address', '地址'),
            array('create_time', '添加时间'),
            array('last_check_time', '最后跟进时间'),
            array('recommend_user_info', '上级', 'true_name'),
        );
        $this->outputAdmins('user', $xlsCell, $list);
        $this->success('', '', $list);
    }

    public function outputAdmins($fileName = '文件名', $headArr, $data)
    {
        $fileName .= "_" . date("Ymd_His", time()) . ".xls";
        $objPHPExcel = new \PHPExcel();
        // Set document properties （设置文档属性）
        $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
            ->setLastModifiedBy("Maarten Balliauw")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        // 设置头信息
        $objPHPExcel->setActiveSheetIndex(0);
        $key = ord('A');
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->getActiveSheet()->setCellValue($colum . '1', $v[1]);
            $key += 1;
        }
        // 获取管理员全部数据

        $column = 2;
        foreach ($data as $key => $rows) { // 行写入
            $span = ord("A");
            foreach ($headArr as $value) {
                if ($rows[$value[0]]) {
                    if (isset($value[2])) {
                        $objPHPExcel->getActiveSheet()->setCellValue(chr($span) . $column, $rows[$value[0]][$value[2]]);
                    } else {
                        $objPHPExcel->getActiveSheet()->setCellValue(chr($span) . $column, $rows[$value[0]]);
                    }
                } else {
                    $objPHPExcel->getActiveSheet()->setCellValue(chr($span) . $column, '');
                }

                $span++;
            }
            $column++;
        }
        $objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save(str_replace('.php', '.xls', 'upload/default/' . date("Ymd", time()) . '/' . $fileName));
        $this->success('导出成功', $this->request->domain() . '/upload/default/' . date("Ymd", time()) . '/' . $fileName);
    }
}
